<template>
  <section>
    <div class="page-wrapper">
      <van-sticky>
        <PageHeader title="登录" />
      </van-sticky>

      <div class="flex flex-col pd20">
        <div class="text-left font-large mt10 mb20 strong">欢迎登录</div>

        <van-cell-group>
          <van-field v-model="user.mobile" required center clearable type="tel" label="手机号" placeholder="请输入手机号" />

          <van-field
            v-model="user.img_captcha"
            required
            center
            clearable
            label="图形码"
            placeholder="请输入图形码">
            <template #button v-if="captchaImage">
              <img :src="captchaImage" height="35" width="100" @click="getCaptcha" />
            </template>
          </van-field>

          <van-field
            v-model="user.sms_captcha"
            required
            center
            clearable
            label="验证码"
            placeholder="请输入短信验证码">
            <template #button>
              <van-button :disabled="sending" size="small" type="primary" @click="sendSms">{{smsLabel}}</van-button>
            </template>
          </van-field>
        </van-cell-group>


        <div class="mt10 bg-color-white text-center btn-submit mt10">
          <van-button size="large" type="primary" round :loading="submitting" loading-text="登录中" @click="login">登录</van-button>
        </div>

        <div class="flex flex-row flex-center mt15 color-gray font-common"><span @click="$router.replace({name: 'UserRegister'})">没有账号？立即注册</span></div>
      </div>
    </div>

    <FullscreenLoading v-if="loadingVisible" />
  </section>
</template>

<script>
  import PageHeader from "../componets/PageHeader";
  import Vue from 'vue';
  import {Sticky, Popup, RadioGroup, Radio, CellGroup, Field, Toast, Button} from 'vant';
  import FullscreenLoading from "../componets/FullscreenLoading";
  import {captchaEntryUri, smsCaptchaSendUri, userLoginByCodeUri, userLoginUri} from "../../common/api";
  import util from '../../assets/js/util';
  Vue.use(Sticky).use(Popup).use(RadioGroup).use(Radio).use(CellGroup).use(Field).use(Toast).use(Button);

  export default {
    components: {
      PageHeader,
      FullscreenLoading
    },
    data() {
      return {
        user: {id: 0, nick: '', mobile: '', img_captcha: '', sms_captcha: ''},
        submitting: false,
        smsLabel: '发送验证码',
        sending: false,
        sessionId: '',
        captchaImage: '',
        loadingVisible: false
      }
    },
    methods: {
      getCaptcha() {
        const that = this;
        const url = captchaEntryUri;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            that.sessionId = data.session_id;
            that.captchaImage = data.captcha;
          }
        }, response => {
          // error callback
        })
      },
      sendSms() {
        if(this.sending) {
          return;
        }
        if(this.user.mobile.length == 0 || this.user.img_captcha.length == 0) {
          Toast('手机号和图形验证码不能为空');
          return
        }
        const that = this;
        const url = smsCaptchaSendUri + '?mobile=' + this.user.mobile + '&img_captcha=' + this.user.img_captcha + '&session_id=' + this.sessionId + '&type=login';
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.getCaptcha();
            Toast.fail(msg);
          } else {
            that.sending = true;
            that.interval = 60;
            that.intv = setInterval(()=>{
              if(that.interval <= 0) {
                that.smsLabel = '发送验证码';
                that.sending = false;
                clearInterval(that.intv);
              } else {
                that.smsLabel = '剩余('+that.interval+')秒';
                that.interval--;
              }
            }, 1000);
            that.getCaptcha();
          }
        }, response => {
          // error callback
        })
      },
      login() {
        if(this.user.mobile.length == 0 || this.user.sms_captcha.length == 0) {
          Toast('手机号和验证码不能为空');
          return
        }
        const that = this;
        const url = userLoginUri + '?mobile=' + this.user.mobile + '&sms_captcha=' + this.user.sms_captcha;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.getCaptcha();
            Toast.fail(msg);
          } else {
            that.EventBus.$emit('OnUserLogined', {user: data.user, member: data.member, method: 'login'});

            const referrer = localStorage.getItem('referrer');
            if(referrer) {
              that.$router.replace(referrer);
            } else {
              that.$router.back();
            }
          }
        }, response => {
          // error callback
        })
      },
      loginByCode() {
        const that = this;
        that.loadingVisible = true;
        const code = util.getQueryVariable('code');
        this.$http.get(userLoginByCodeUri + '?code=' + code).then(response => {
          that.loadingVisible = false;
          let {code, msg, data} = response.body
          if (code != 0) {
            // Toast(msg);
            that.getCaptcha();
          } else {
            that.EventBus.$emit('OnUserLogined', {user: data.user, member: data.member, method: 'login'});

            window.sessionStorage.setItem('wx_auth', true);

            const referrer = localStorage.getItem('referrer');
            if(referrer) {
              that.$router.replace(referrer);
            } else {
              that.$router.replace({name: 'Home'})
            }
          }
        }, response => {
          // error callback
          that.loadingVisible = false;
        })
      }
    },
    created: function () {
      if(isWxServiceEnable) {
        if(util.getQueryVariable('code')) {
          this.loginByCode();
        } else {
          const rUrl = window.location.protocol + '//' + window.location.host + this.$router.history.base + '/user_login';
          const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+WECHAT_APP_ID+'&redirect_uri='+encodeURIComponent(rUrl)+'&response_type=code&scope=snsapi_base&state=#wechat_redirect';
          window.location.href = href;
        }
      }
    },
    mounted: function () {
      this.getCaptcha();
    }
  }
</script>

<style scoped>
  .page-wrapper {
    background: #FFFFFF;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
</style>
